#include "Alphabet.h"
#include "Image.h"
#include "Font.h"

#include <string>
#include <map>
#include <vector>

using neiderra::rendering::Alphabet;
using neiderra::rendering::Image;
using neiderra::rendering::RenderingFont;
using std::string;
using std::map;
using std::vector;

Alphabet::Alphabet(RenderingFont* font): iObject()
{
	_font = font;
	_base = 0;
}

Alphabet::~Alphabet()
{
	map<unsigned, Image*>::iterator i;
	for(i=_letters.begin();i!=_letters.end();++i)
	{
		Image* img = i->second;
		if(img)
			delete img;
	}
}

Image* Alphabet::getLetter(unsigned c)
{
	return _letters[c];
}

Image* Alphabet::compose(const string& str)
{
	int imgW=0;
	int imgH=0;

	const int delta=3;

	// imgW, imgH
	const int strlen = str.size();
	unsigned *widths = new unsigned[strlen];
	vector<Image*> images;
	
	for(int i=0;i<strlen;i++)
	{
		char c = str[i];
		Image* img = _letters[c];
		if(!img) continue;
		const unsigned w = img->getWidth();

		imgW += w;
		widths[i] = w+delta;


		if(imgH < img->getHeight())
			imgH = img->getHeight();

		images.push_back(img);
	}

	Image* strImg = new Image(imgW+delta*strlen, imgH);

	int pen_x=0, pen_y=0;
	for(int i=0;i<strlen;i++)
	{
		Image* img = images[i];
		if(!img) continue;
		strImg->paste(pen_x, pen_y, img);
		pen_x += widths[i];
	}

	delete[] widths;
	return strImg;
}

void Alphabet::setLetterBase(unsigned base)
{
    _base = base;
}

void Alphabet::setLetter(unsigned n, Image* a)
{
	_letters[n] = a;
}

RenderingFont* Alphabet::getFont()
{
	return _font;
}
